<?php
/**
 * Created by PhpStorm.
 * User: liu
 * Date: 17-4-1
 * Time: 上午10:51
 */

namespace Cframe;


class Hook {
    private static $hook_list = [];

    public static function add_action($name,$function,$frist = false){
        if (array_key_exists($name,static::$hook_list)){
            if ($frist){
                array_unshift(static::$hook_list[$name],$function);
            }else{
                static::$hook_list[$name][] = $function;
            }
        }else{
            static::$hook_list[$name][] = $function;
        }
    }

    public static function listen(){
        $attr = func_get_args();
        $name = array_shift($attr);
        if (isset(static::$hook_list[$name])){
            foreach (static::$hook_list[$name] as $val){
                call_user_func_array($val,$attr);
            }
        }
    }

    public static function import(array $tag){
        foreach ($tag as $key=>$value){
            static::add_action($key,$value);
        }
    }

    public static function save(){
        if (!empty(static::$hook_list)){
            Cache::set("Hook.copy",static::$hook_list);
        }
    }

    public static function load(){
        $config = Config::get("hook");
        if (is_array($config) && isset($config['is_save']) && $config['is_save'] === true){
            $copy = Cache::load("Hook.copy");
            if (is_array($copy) && !empty($copy)){
                static::$hook_list = array_merge(static::$hook_list,$copy);
            }
        }
    }
}